import { realEstateAdd, getProjectAndLand, realEstateEdit, validateCardNumber, getAssetRegistrationList, getRealEstate, validateAssetsName } from "@/views/property-info-sys/proprietary-information/api/propertietar.js"
import { getAllProject } from "@/views/property-info-sys/project-manage/api/project_manage"
import { getDivision } from '@/admin/api/division'
import relevancyProperty from '../component/relevancy-property'
import governmentInvestment from '../component/new-government'
import BaseLoad from '@/assets/vue-mixin/BaseLoad'
import { mapGetters } from "vuex";
export default {
    data () {
        let doubleValidate = (rule, value, callback) => {
            if (value === '' || value === null) return callback()
            let reg = /^[0-9]+(.[0-9]{1,2})?$/;
            let lable = rule.message;
            if (!reg.test(value)) {
                return callback(new Error("数值格式错误（最多保留两位小数）"));
            } else {
                if (value > 9999999999) {
                    return callback(new Error("最大值不超过9999999999"));
                } else {
                    callback();
                }
            }
        };
        let isInt = (rule, value, callback) => {
            if (value === '' || value === 0 || value === null) return callback()
            if (!Number(value)) {
                callback(new Error('请输入正整数'));
            } else {
                const re = /^[0-9]*[1-9][0-9]*$/;
                const rsCheck = re.test(value);
                console.log(value, " 匹配结果L", re.test(value))
                if (!rsCheck) {
                    callback(new Error('请输入正整数'));
                } else {
                    callback();
                }
            }
        }
        let validateCarNum = (rule, value, callback) => {
            if (!value) {
                callback()
            }
            this.validateOnly(value, callback)
        };
        let validateAssetName = (rule, value, callback) => {
            if (!value) {
                callback()
            }
            this.validateAssetsOnly(value, callback)
        };
        return {
            governmentInvestmentFlag: false,
            governmentInvestmentId: '',
            uploadFileList: [],
            modelType: 'propertyCard',
            loading: false,
            isAdd: true,
            addCardType: '10',
            id: '',
            proprietaryTypes: [],
            planUses: [],
            landUses: [],
            projects: [],
            provinces: [],
            citys: [],
            countys: [],
            assetRegistrationTypes: [],
            assetClassificationTypes: [],
            useStatusTypes: [],
            acquisitionMethodTypes: [],
            valueTypes: [],
            ownershipCertificateTypes: [],
            ownershipNatureTypes: [],
            buildingStructureTypes: [],
            depreStatusTypes: [],
            projectStreet: [],
            communityNames: [],
            propForm: {
                assetFixedWarehousingId: '',
                cardType: '',
                cardNum: '',
                registrationPrice: '',
                registrationDate: '',
                projectId: '',
                landType: '',
                planningType: '',
                completionTime: '',
                obligee: '',
                assetCode: '',
                assetClassification: '',
                assetName: '',
                useStatus: '',
                acquisitionMethod: '',
                acquisitionDate: '',
                investmentAcquisitionDate: '',
                valueType: '',
                registrationFee: '',
                taxation: '',
                value: '',
                number: '',
                measurementUnit: '',
                landArea: '',
                propertyRightForm: '',
                ownershipCertificateNo: '',
                issueData: '',
                ownershipPeriod: '',
                ownershipCertificate: '',
                location: '',
                ownershipNature: '',
                selfUseArea: '',
                selfUseValue: '',
                buildingStructure: '',
                depreStatus: '',
                accumDepre: '',
                estimatedLife: '',
                initDepreMonth: '',
                lastDepreMonth: '',
                salvageValue: '',
                isCard: '2',
                landNumber: '',
                landAreaCard: '',
                assetRegistrationId: '1',
                area: '',
                address: '',
                addressInfo: '',
                provinceCode: '',
                cityCode: '',
                countyCode: '',
                communityName: '',
                roomStreet: '',
                remarks: '',
                roomIds: [],
                warehousingStatus: '' //入库状态
            },
            rules: {
                isCard: [
                    { required: true, message: "请选择是否有不动产证", trigger: "change" }
                ],
                cardType: [
                    { required: true, message: "请选择证件类型", trigger: "change" }
                ],
                cardNum: [
                    { required: true, message: "请输入不动产证编号", trigger: "change" },
                    { min: 0, max: 30, message: "长度在0-30个字符串", trigger: "blur" },
                    { validator: validateCarNum, trigger: "blur" }
                ],
                assetClassification: [
                    { required: true, message: "请选择(国标码)资产分类代码", trigger: "change" }
                ],
                assetName: [
                    { required: true, message: "请输入资产名称", trigger: "blur" },
                    { validator: validateAssetName, trigger: "change" }
                ],/*
                useStatus: [
                    { required: true, message: "请选择使用状况", trigger: "change" }
                ],
                acquisitionMethod: [
                    { required: true, message: "请选择取得方式", trigger: "change" }
                ],
                acquisitionDate: [
                    { required: true, message: "请选择取得日期", trigger: "change" },
                ],
                investmentAcquisitionDate: [
                    { required: true, message: "请选择投入使用日期", trigger: "change" },
                ],
                valueType: [
                    { required: true, message: "请选择价值类型", trigger: "change" },
                ],*/
                propertyPrice: [
                    { validator: doubleValidate, trigger: "blur" },
                ],
                registrationDate: [
                    { required: true, message: "请选择登记日期", trigger: "blur" },
                ],
                projectId: [
                    { required: true, message: "请选择所属项目", trigger: "blur" },
                ],
                buildingArea: [
                    { required: true, message: "请输入建筑面积", trigger: "blur" },
                    { validator: doubleValidate, trigger: "blur" },
                ],
                unitConstractionArea: [
                    { required: true, message: "请输入套内面积", trigger: "blur" },
                    { validator: doubleValidate, trigger: "blur" },
                ],
                landType: [
                    { required: true, message: "请选择土地用途", trigger: "blur" }
                ],
                planningType: [
                    { required: true, message: "请选择规划用途", trigger: "blur" }
                ],
                completionTime: [
                    { required: true, message: "请选择竣工时间", trigger: "blur" }
                ],
                serviceLife: [
                    { required: true, message: "请选择使用年限", trigger: "blur" }
                ],
                useTime: [
                    { required: true, message: "请选择使用期限", trigger: "blur" },
                    { validator: doubleValidate, trigger: "blur" },
                ],
                obligee: [
                    { required: true, message: "请输入权利人", trigger: "blur" },
                    { min: 0, max: 30, message: "长度在0-30个字符串", trigger: "blur" },
                ],
                landNumber: [
                    { required: true, message: "请输入宗地号", trigger: "blur" },
                    { min: 0, max: 30, message: "长度在0-30个字符串", trigger: "blur" },
                ],
                landArea: [
                    // { required: true, message: "请输入宗地面积", trigger: "blur" },
                    { validator: doubleValidate, trigger: "blur" },
                ],
                registrationPrice: [
                    { required: false, message: "登记价/评估价输入错误", trigger: "blur" },
                    { validator: doubleValidate, trigger: "blur" },
                ],
                registrationFee: [
                    { required: false, message: "登记费输入错误", trigger: "blur" },
                    { validator: doubleValidate, trigger: "blur" },
                ],
                taxation: [
                    { required: false, message: "税费输入错误", trigger: "blur" },
                    { validator: doubleValidate, trigger: "blur" },
                ],
                value: [
                    { required: false, message: "价值输入错误", trigger: "blur" },
                    { validator: doubleValidate, trigger: "blur" },
                ],
                number: [
                    { required: false, message: "数量输入错误", trigger: "blur" },
                    { validator: isInt, trigger: "blur" },
                ],
                measurementUnit: [
                    // { required: false, message: "计量单位输入错误", trigger: "blur" },
                    { validator: doubleValidate, trigger: "blur" },
                ],
                landAreaCard: [
                    { required: false, message: "宗地面积输入错误", trigger: "blur" },
                    { validator: doubleValidate, trigger: "blur" },
                ],
                selfUseArea: [
                    { required: false, message: "自用面积输入错误", trigger: "blur" },
                    { validator: doubleValidate, trigger: "blur" },
                ],
                selfUseValue: [
                    { required: false, message: "自用价值输入错误", trigger: "blur" },
                    { validator: doubleValidate, trigger: "blur" },
                ],
                estimatedLife: [
                    { required: false, message: "预计使用年限输入错误", trigger: "blur" },
                    { validator: isInt, trigger: "blur" },
                ],
                ownershipPeriod: [
                    { required: false, message: "权属年限输入错误", trigger: "blur" },
                    { validator: isInt, trigger: "blur" },
                ],
                initDepreMonth: [
                    { required: false, message: "初始折旧月份输入错误", trigger: "blur" },
                    { validator: isInt, trigger: "blur" },
                ],
                lastDepreMonth: [
                    { required: false, message: "上次折旧月份输入错误", trigger: "blur" },
                    { validator: isInt, trigger: "blur" },
                ],
                salvageValue: [
                    { required: false, message: "请输入残值率", trigger: "blur" },
                    { validator: doubleValidate, trigger: "blur" },
                ],
                accumDepre: [
                    { required: false, message: "累计折旧额输入错误", trigger: "blur" },
                    { validator: doubleValidate, trigger: "blur" },
                ],
                provinceCode: [
                    { required: true, message: "请选择地址", trigger: "blur" }
                ],
                cityCode: [
                    { required: true, message: "请选择市", trigger: "blur" }
                ],
                countyCode: [
                    { required: true, message: "请选择县区", trigger: "blur" }
                ],
                address: [
                    { required: true, message: "请输入详细地址", trigger: "blur" },
                    { min: 0, max: 50, message: "长度在0-50个字符串", trigger: "blur" },
                ],
                remark: [
                    { min: 0, max: 100, message: "长度在0-10个字符串", trigger: "blur" },
                ]

            },
            // hxf-0918-证件类型
            cardTypeList: [],
            cardTypes: [],
            cardTypesY: [],
            cardTypesT: [],
            // hxf-0918-不动产信息
            cardNum: '不动产证编号',
            // hxf-0923-政府项目传值
            assetRegistrationId: ''
        }
    },
    methods: {
        // 修改时初始化地址选择器
        async initCitySelector () {
            await getRealEstate(this.id).then((res) => {
                this.isAdd = false;
                this.propForm = res.data.data
                if (this.propForm.assetRegistrationId !== '1') {
                    this.governmentInvestmentFlag = true
                    this.governmentInvestmentId = this.propForm.assetRegistrationId
                    this.$refs.governmentInvestment.handleChangeAssetRegistration(this.governmentInvestmentId)
                    this.propForm.assetRegistrationId = '0'
                } else {
                    this.governmentInvestmentFlag = false
                }
                /*//获取省市县区下拉数据
                this.queryProvince();
                if (this.propForm.provinceCode) {
                    this.queryCitys(this.propForm.provinceCode)
                }
                if (this.propForm.cityCode) {
                    this.queryCounty(this.propForm.cityCode)
                }*/
            }).catch((e) => {
                this.$message({
                    type: "error",
                    message: "数据获取失败!",
                });
            });
        },
        /*queryProvince() {
           getDivision({ "lazy": true, parentId: "000000" }).then(rep => {
               let rep_province = rep.data.data
               this.provinces = rep_province.map(p => {
                   return { "label": p.divisionName, "value": p.divisionCode }
               })
           })
       },
      //获取城市
       queryCitys(val) {
           getDivision({ "lazy": true, parentId: val }).then(rep => {
               let rep_city = rep.data.data
               this.citys = rep_city.map(p => {
                   return { "label": p.divisionName, "value": p.divisionCode }
               })

           })
       },
       //获取县区
       queryCounty(val) {
           getDivision({ "lazy": true, parentId: val }).then(rep => {
               let rep_county = rep.data.data
               this.countys = rep_county.map(p => {
                   return { "label": p.divisionName, "value": p.divisionCode }
               })
           })
       },
       //选择省清空下级
       handleBlurProvince() {
           this.propForm.cityCode = ''
           this.propForm.countyCode = ''
           this.propForm.address = ''
       },
       //选择市清空下级
       handleBlurCity() {
           this.propForm.countyCode = ''
           this.propForm.address = ''
       },
       //选择县清空下级
       handleBlurCounty() {
           this.propForm.address = ''
       },*/
        //验证不动产证编号是否存在
        validateOnly (value, callback) {
            validateCardNumber({ "cardId": this.id, "cardNum": value }).then(rep => {
                let vr = rep.data.data
                if (vr === 0) {
                    return callback();
                } else {
                    return callback(new Error("该编号不能重复"));
                }
            })
        },
        //验证资产名称是否存在
        validateAssetsOnly (value, callback) {
            validateAssetsName({ 'assetsName': value, 'assetFixedWarehousingId': this.id }).then(res => {
                let sum = res.data.data
                if (sum === 0) {
                    return callback();
                } else {
                    return callback(new Error("资产名称不能重复"));
                }
            })
        },
        submitForm (formName) {
            let propertyRow = this.$refs["relevancyProperty"].commitSelectRow
            if (!propertyRow || propertyRow.length == 0) {
                this.$alert("请选择关联物业信息！")
                return false;
            }
            if (this.governmentInvestmentFlag === true && this.$refs.governmentInvestment.commitSelectRow.length === 0) {
                this.$alert("请选择政府投资项目！")
                return false;
            }
            //多表单同步验证 Promise
            this.propForm.area = this.getCardTypeValue(this.propForm.cityCode, this.cityAssembly)
                + this.getCardTypeValue(this.propForm.countyCode, this.districtCollection)
                + this.getCardTypeValue(this.propForm.roomStreet, this.projectStreet)
                + this.getCardTypeValue(this.propForm.communityName, this.communityNames)
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    this.$refs.propertyCardFileUpload.submit();
                } else {
                    this.$message.warning('请完善必填项！')
                }
            })
        },
        saveFormData (id) {
            if (id && this.isAdd) {
                this.propForm.assetFixedWarehousingId = id
            }
            let propertyRow = this.$refs["relevancyProperty"].commitSelectRow
            propertyRow = propertyRow.map(pr => {
                return pr.roomId
            })
            this.propForm.roomIds = propertyRow
            if (this.$refs.governmentInvestment.commitSelectRow.length > 0 && this.propForm.assetRegistrationId !== '1') {
                if (this.assetRegistrationTypes[0] === undefined) {
                    this.propForm.assetRegistrationId = this.governmentInvestmentId
                } else {
                    this.propForm.assetRegistrationId = this.assetRegistrationTypes[0].assetRegistrationId
                }
            }
            this.loadAction('数据加载中')
            if (this.isAdd) {
                realEstateAdd(this.propForm).then((rep) => {
                    this.loadClose()
                    this.$message.success("保存成功");
                    this.closeNowRouter();
                }).catch((e) => {
                    this.loadClose()
                    this.$message.error("保存失败");

                })
            } else {
                realEstateEdit(this.propForm).then((rep) => {
                    this.loadClose()
                    this.$message.success("修改成功");
                    //关闭当前新增页，暂时没找到好办法
                    this.closeNowRouter();
                }).catch((e) => {
                    this.loadClose()
                    this.$message.error("修改失败");
                });
            }
        },
        closeNowRouter () {
            //关闭当前新增页，暂时没找到好办法
            this.$store.commit("delHistoryRoute", this.$route.fullPath);
            // this.$parent.$children[2].closeTab('current')
            //跳转
            sessionStorage.setItem('cardType',this.propForm.cardType)
            this.$router.push("/property-info-sys/proprietary-info");
        },
        onSuccess (rep, file, fileList) {
            //文件上传成功，开始保存表单
            if (fileList !== undefined && fileList.length > 0) {
                if (rep.data) {
                    this.saveFormData(rep.data)
                } else {
                    this.err('文件上传失败')
                }
            } else {
                this.saveFormData(rep.data)
            }
        },
        // hxf-0914-套内面积失焦校验
        handleAreaCompared () {
            if (Number(this.propForm.unitConstractionArea) > Number(this.propForm.buildingArea)) {
                this.$message.error('套内面积不能大于建筑面积！')
                this.propForm.unitConstractionArea = ''
            }
        },
        // hxf-0919-是否有不动产证改变事件
        handleARealEstateCertificate () {
            this.propForm.cardType = ''
        },
        // hxf-0919-监听证件类型
        handleChangeCardType () {
            if (this.propForm !== null) {
                if (this.propForm.isCard === '' || this.propForm.isCard === null || this.propForm.isCard === undefined) {
                    this.$message.error('请先选择是否有不动产证！');
                    this.propForm.cardType = '';
                    this.propForm.cardNum = ''
                } else {
                    if (this.propForm.cardType === '20') {
                        this.cardNum = '移交协议编号'
                        this.propForm.cardNum = ''
                    } else if (this.propForm.cardType === '30') {
                        this.cardNum = '第三方评估机构报告编号'
                        this.propForm.cardNum = ''
                    } else {
                        this.cardNum = '不动产证编号'
                        this.propForm.cardNum = ''
                    }
                }
            }
        },
        // hxf-0923-政府投资项目选中
        handleChangeAssetRegistration () {
            if (this.propForm.assetRegistrationId === '0') {
                this.governmentInvestmentFlag = true
                // this.governmentInvestmentId = this.assetRegistrationTypes[0].assetRegistrationId
            } else {
                this.governmentInvestmentFlag = false
            }
        },
        changeTime () {
            let startTm = this.propForm.acquisitionDate;
            let endTm = this.propForm.investmentAcquisitionDate;
            if (endTm && startTm) {
                if (!this.compare(endTm, startTm)) {
                    this.$message.error('取得日期不能晚于投入使用日期！')
                    this.propForm.investmentAcquisitionDate = ''
                }
            }
        },
        compare (date1, date2) {
            let dates1 = new Date(date1);
            let dates2 = new Date(date2);
            if (dates1 >= dates2) {
                return true
            } else {
                return false
            }
        },
        handleBulr () {
            if (Number(this.propForm.salvageValue) > 100) {
                this.$message.error('残值率不能大于100！')
                this.propForm.salvageValue = ''
            }
        },
        //政府投资项目
        handleSelectRow (item) {
            this.assetRegistrationTypes = item.list
        },
        //选择所属项目
        handleChangeProjectId (val) {
            getProjectAndLand(val).then(res => {
                if (res.data.code === 0) {
                    // console.log('res.data.data--',res.data.data)
                    this.propForm.landNumber = res.data.data.parcelNum
                    this.propForm.landAreaCard = res.data.data.parcelArea
                    this.propForm.landType = res.data.data.landUse
                    this.propForm.cityCode = res.data.data.areaCode.split('-')[0]
                    this.propForm.countyCode = res.data.data.areaCode.split('-')[1]
                    this.propForm.roomStreet = res.data.data.projectStreet
                    this.propForm.communityName = res.data.data.communityName
                    this.propForm.address = res.data.data.addressInfo
                }
            })
        },
        //回显时对应value显示label
        getCardTypeValue (num, sum) {
            let arr = sum.filter(e => e.value === num)
            if (arr.length > 0) {
                return arr[0].label
            } else {
                return num
            }
        },
    },
    components: {
        relevancyProperty, governmentInvestment
    },
    mixins: [BaseLoad],
    computed: {
        selectProvice: function () {
            return this.provinces.find(p => p.value == this.propForm.provinceCode)
        },
        selectCity: function () {
            return this.citys.find(p => p.value == this.propForm.cityCode)
        },
        selectCounty: function () {
            return this.countys.find(p => p.value == this.propForm.countyCode)
        },
        chArea: function () {
            let p = this.selectProvice ? this.selectProvice.label : ''
            let c = this.selectCity ? this.selectCity.label : ''
            let y = this.selectCounty ? this.selectCounty.label : ''
            return p + c + y
        },
        ...mapGetters({
            cityAssembly: 'getCityAssembly',
            districtCollection: 'getDistrictCollection',
        })
    },
    created () {
        getAllProject().then(rep => {
            let projectData = rep.data.data
            if (projectData) {
                this.projects = projectData.map(p => {
                    return { label: p.projectName, value: p.projectId }
                })
            }
        })
        if (this.$route.params.id) {
            this.propForm.assetFixedWarehousingId = this.$route.params.id
            if (this.propForm.assetFixedWarehousingId) {
                this.id = this.propForm.assetFixedWarehousingId
                this.initCitySelector()
                // this.$refs.governmentInvestment.assetRegistrationId = this.propForm.assetRegistrationId
                // this.$refs.governmentInvestment.handleChangeAssetRegistration()
            }
        } else {
            //获取各个tabl页新增的时候自动匹配证件类型
            let cardType = this.$route.params.cardType;
            if (cardType) {


                //新增跳转过来的不是不动产页，则是否有不动产证默认为否，且不显示
                if (cardType !== '10') {
                    this.propForm.isCard = '1';
                }
                this.addCardType = cardType
                this.propForm.cardType = cardType;
                this.handleChangeCardType();
            }
        }


        /* getAssetRegistrationList().then(res => {
             if (res.data.code === 0) {
                 this.assetRegistrationTypes = res.data.data.filter(item => item.projectName !== "")
             }
         })*/
        this.propForm.cityCode = this.cityAssembly[0].value
        this.propForm.countyCode = this.districtCollection[0].value
        this.projectStreet = this.getDict('streets')
        this.communityNames = this.getDict('community_names')
        this.proprietaryTypes = this.getDict('asset-property-right-form')
        this.planUses = this.getDict('plan_uses')
        this.landUses = this.getDict('land_uses')
        this.cardTypeList = this.getDict('real_estate_card_type').slice(1, 3)
        this.cardTypes = this.getDict('real_estate_card_type').slice(0, 1)
        this.cardTypesY = this.getDict('real_estate_card_type').slice(1, 2)
        this.cardTypesT = this.getDict('real_estate_card_type').slice(2, 3)
        this.assetClassificationTypes = this.getDict('asset-classification')
        this.useStatusTypes = this.getDict('asset-use-status')
        this.acquisitionMethodTypes = this.getDict('asset-acquisition-method')
        this.valueTypes = this.getDict('asset-value-type')
        this.ownershipCertificateTypes = this.getDict('asset-ownership-certificate')
        this.ownershipNatureTypes = this.getDict('asset-ownership-nature')
        this.buildingStructureTypes = this.getDict('asset-building-structure')
        this.depreStatusTypes = this.getDict('asset_depreciation_status')
        if (this.proprietaryTypes.length > 0 && this.proprietaryTypes !== null) {
            for (let i = 0; i < this.proprietaryTypes.length; i++) {
                this.proprietaryTypes[i].value = parseInt(this.proprietaryTypes[i].value)
            }
        }
        if (this.assetClassificationTypes.length > 0 && this.assetClassificationTypes !== null) {
            for (let i = 0; i < this.assetClassificationTypes.length; i++) {
                this.assetClassificationTypes[i].value = parseInt(this.assetClassificationTypes[i].value)
            }
        }
        if (this.useStatusTypes.length > 0 && this.useStatusTypes !== null) {
            for (let i = 0; i < this.useStatusTypes.length; i++) {
                this.useStatusTypes[i].value = parseInt(this.useStatusTypes[i].value)
            }
        }
        if (this.acquisitionMethodTypes.length > 0 && this.acquisitionMethodTypes !== null) {
            for (let i = 0; i < this.acquisitionMethodTypes.length; i++) {
                this.acquisitionMethodTypes[i].value = parseInt(this.acquisitionMethodTypes[i].value)
            }
        }
        if (this.valueTypes.length > 0 && this.valueTypes !== null) {
            for (let i = 0; i < this.valueTypes.length; i++) {
                this.valueTypes[i].value = parseInt(this.valueTypes[i].value)
            }
        }
        if (this.ownershipCertificateTypes.length > 0 && this.ownershipCertificateTypes !== null) {
            for (let i = 0; i < this.ownershipCertificateTypes.length; i++) {
                this.ownershipCertificateTypes[i].value = parseInt(this.ownershipCertificateTypes[i].value)
            }
        }
        if (this.ownershipNatureTypes.length > 0 && this.ownershipNatureTypes !== null) {
            for (let i = 0; i < this.ownershipNatureTypes.length; i++) {
                this.ownershipNatureTypes[i].value = parseInt(this.ownershipNatureTypes[i].value)
            }
        }
        if (this.buildingStructureTypes.length > 0 && this.buildingStructureTypes !== null) {
            for (let i = 0; i < this.buildingStructureTypes.length; i++) {
                this.buildingStructureTypes[i].value = parseInt(this.buildingStructureTypes[i].value)
            }
        }
    },
    mounted () {
        /*if(this.isAdd){
            this.queryProvince()
        }*/
        this.$refs.propertyCardFileUpload.getFiles(this.id)

    },
};
